'''
Copyright 2010 Indra Bagus <indra.bagus@gmail.com> 
    
Licensed under the Apache License, Version 2.0 (the "License"); 
you may not use this file except in compliance with the License. 
You may obtain a copy of the License at 

    http://www.apache.org/licenses/LICENSE-2.0 
    
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, 
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. 
'''

import re
import array


class CArrayFormat(object):
    BYTE_SIZE   = 1
    SHORT_SIZE  = 2
    WORD_SIZE   = 4
    def __init__(self,filename,bytelength = BYTE_SIZE):
        self._hfile = open(filename,'r')
        self._regex_hexa = re.compile('0x([\d,a-f,A-F]{%d,%d})' % (bytelength*2,bytelength*2))
        self.bytelength = bytelength
        
    def ReadNextPayload(self):
        line = self._hfile.readline()
        if(self.bytelength == 1 ):
            streamarr = array.array('B')
        elif(self.bytelength == 2):
            streamarr = array.array('H')
        else:
            streamarr = array.array('I')        
        while line:

            findbeginend = re.search('{', line)
            if findbeginend == None:
                line = self._hfile.readline()
                continue 
            else:
                while line :
                    wordslist = self._regex_hexa.findall(line)
                    for word in wordslist:
                        streamarr.append(int(word,16))
                    if re.search('}',line):
                        break
                    line = self._hfile.readline()
                # break from the "while line" looping
                break
            
        if(len(streamarr) == 0):
            return None
        streamarr.byteswap()
        return streamarr.tostring()
            
        


        


